
package com.hlkj.pay.app.merchant.ext.impl.easypay.ext;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.json.JSONObject;
import com.hlkj.framework.common.util.id.IdUtils;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.app.merchant.ext.dto.order.ChannelPayOrderQueryContext;
import com.hlkj.pay.app.merchant.ext.dto.order.ChannelRefundPayOrderContext;
import com.hlkj.pay.app.merchant.ext.impl.easypay.constant.EasyPayConstant;
import com.hlkj.pay.app.merchant.ext.impl.easypay.dto.EasyPayConfig;
import com.hlkj.pay.app.merchant.ext.impl.easypay.dto.EasypayAppChannelParams;
import com.hlkj.pay.app.merchant.ext.impl.easypay.dto.req.SeparateInfo;
import com.hlkj.pay.app.merchant.ext.impl.easypay.dto.req.SeparateOrderDetailList;
import com.hlkj.pay.app.merchant.ext.impl.easypay.utils.EasyPaySignUtil;
import com.hlkj.pay.app.merchant.ext.impl.easypay.utils.HttpUtils;
import com.hlkj.pay.dto.order.PayOrderFundDto;
import com.hlkj.pay.enums.PayOrderEnums;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAppChannelDO;
import com.hlkj.pay.infrastructure.model.order.PayOrderDO;
import com.hlkj.pay.infrastructure.model.order.RefundOrderDO;
import com.hlkj.pay.infrastructure.model.pay.ProviderChannelConfigDO;
import com.hlkj.pay.util.DateUtils;
import com.hlkj.pay.util.MerchantUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * 易生 正扫 反扫 通用处理
 * 
 * @author HlpayTeam
 * @date 2024/10/11 16:22
 */
@Slf4j
@Repository
@RequiredArgsConstructor
public class EasyPaySceneCommonPayOrder {

    /**
     * 易生查询支付订单
     *
     * @param channelPayOrderQueryContext
     */
    public void commonQueryChannelPayOrder(ChannelPayOrderQueryContext channelPayOrderQueryContext) {
        ProviderChannelConfigDO providerChannelConfigDO = channelPayOrderQueryContext.getProviderChannelConfigDO();
        String channelConfig = providerChannelConfigDO.getParamsConfig();
        // 配置转换
        EasyPayConfig easyPayConfig = JsonUtils.parseObject(channelConfig, EasyPayConfig.class);
        PayOrderDO payOrderDO = channelPayOrderQueryContext.getPayOrderDO();
        MerchantAppChannelDO merchantAppChannelDO = channelPayOrderQueryContext.getMerchantAppChannelDO();
        try {

            Map<String, Map<String, Object>> reqBody = new HashMap<>();
            Map<String, Object> reqInfo = new HashMap<>();
            reqInfo.put("mchtCode", merchantAppChannelDO.getSubMchId());
            reqBody.put("reqInfo", reqInfo);

            Map<String, Object> reqOrderInfo = new HashMap<>();
            reqOrderInfo.put("orgTrace", IdUtils.getSnowflake().nextIdStr());
            reqOrderInfo.put("oriOrgTrace", payOrderDO.getPayOrderNo());
            reqOrderInfo.put("oriTransDate", DateUtils.dateToString(payOrderDO.getCreateTime(), DatePattern.PURE_DATE_PATTERN));
            reqBody.put("reqOrderInfo", reqOrderInfo);

            Map<String, Object> payInfo = new HashMap<>();
            payInfo.put("transDate", DateUtils.dateToString(payOrderDO.getCreateTime(), DatePattern.PURE_DATE_PATTERN));
            reqBody.put("payInfo", payInfo);

            Map<String, Object> reqHeader = new HashMap<>();
            reqHeader.put("reqId", easyPayConfig.getReqId());
            reqHeader.put("transTime", DateUtils.dateToString(payOrderDO.getCreateTime(), DatePattern.PURE_DATETIME_PATTERN));
            Map<String, Object> params = new HashMap<>();
            params.put("reqHeader", reqHeader);
            params.put("reqBody", reqBody);
            params.put("reqSign", EasyPaySignUtil.sign(params, easyPayConfig.getRsaPrivateKey()));

            log.info("易生订单查询req参数:{}", JsonUtils.toJsonString(params));
            String url = domain(channelPayOrderQueryContext.isTest()) + EasyPayConstant.TRADE_QUERY;
            String response = HttpUtils.post(url, params);
            log.info("易生订单查询返回参数:{}", response);
            // 响应报文验签
            JSONObject res = JsonUtils.parseObj(response);
            JSONObject resHeader = res.getJSONObject("rspHeader");
            JSONObject rspBody = res.getJSONObject("rspBody");
            if ("000000".equals(resHeader.getStr("rspCode"))) {
                JSONObject respStateInfo = rspBody.getJSONObject("respStateInfo");
                if (!"000000".equals(respStateInfo.getStr("respCode"))) {
                    String respDesc = respStateInfo.getStr("respDesc");
                    channelPayOrderQueryContext.setProcessStatus(Boolean.FALSE);
                    if (StringUtils.hasText(respDesc)) {
                        channelPayOrderQueryContext.setRemark(respDesc);
                    }
                    else {
                        channelPayOrderQueryContext.setRemark("易生提交支付订单查询返回错误信息为空,错误码为:" + respStateInfo.getStr("respCode"));
                    }
                    return;
                }
                PayOrderDO updartePayOrderDO = new PayOrderDO();
                switch (respStateInfo.getStr("transState")) {
                    case "0":
                        if (rspBody.containsKey("settleRespParamInfo")) {
                            JSONObject settleRespParamInfo = rspBody.getJSONObject("settleRespParamInfo");
                            updartePayOrderDO.setSuccessTime(DateUtils.shanghaiDate(settleRespParamInfo.getStr("settleTime")));
                        }
                        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.SUCCESS.getCode());
                        break;
                    case "X":
                        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.FAIL.getCode());
                        break;
                    case "C":
                        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.CLOSE.getCode());
                        break;
                    case "1":
                        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.PAYING.getCode());
                        break;
                    case "A":
                        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.CANCEL.getCode());
                        break;
                }

                JSONObject respOrderInfo = rspBody.getJSONObject("respOrderInfo");
                updartePayOrderDO.setInsOrderNo(respOrderInfo.getStr("outTrace"));
                updartePayOrderDO.setChannelOrderNo(respOrderInfo.getStr("pcTrace"));
                if (respOrderInfo.containsKey("userId")) {
                    updartePayOrderDO.setUserId(respOrderInfo.getStr("userId"));
                } else {
                    if (respOrderInfo.containsKey("wxRespParamInfo")) {
                        JSONObject wxRespParamInfo = respOrderInfo.getJSONObject("wxRespParamInfo");
                        updartePayOrderDO.setUserId(wxRespParamInfo.getStr("openId"));
                    }
                    if (respOrderInfo.containsKey("aliRespParamInfo")) {
                        JSONObject aliRespParamInfo = respOrderInfo.getJSONObject("aliRespParamInfo");
                        updartePayOrderDO.setUserId(aliRespParamInfo.getStr("buyerId"));
                    }
                }

                JSONObject settleRespParamInfo = rspBody.getJSONObject("settleRespParamInfo");
                if (!Objects.isNull(settleRespParamInfo) && settleRespParamInfo.containsKey("finalAmt")) {
                    updartePayOrderDO.setSettlementAmount(MerchantUtils.divide(new BigDecimal(settleRespParamInfo.getStr("finalAmt")), new BigDecimal(100)));
                }
                channelPayOrderQueryContext.setUpdartePayOrderDO(updartePayOrderDO);
            }
            else {
                String respDesc = resHeader.getStr("rspInfo");
                channelPayOrderQueryContext.setProcessStatus(Boolean.FALSE);
                if (StringUtils.hasText(respDesc)) {
                    channelPayOrderQueryContext.setRemark(respDesc);
                }
                else {
                    channelPayOrderQueryContext.setRemark("易生提交支付订单查询返回错误信息为空,错误码为:" + resHeader.getStr("rspCode"));
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("易生查询支付订单请求失败 message:{}", e.getMessage(), e);
            channelPayOrderQueryContext.setRemark("易生查询支付订单请求失败,失败信息" + e.getMessage());
            channelPayOrderQueryContext.setProcessStatus(Boolean.FALSE);
        }
    }

    /**
     * 易生关闭订单
     *
     * @param channelPayOrderQueryContext
     */
    public void commonCloseChannelPayOrder(ChannelPayOrderQueryContext channelPayOrderQueryContext) {
        ProviderChannelConfigDO providerChannelConfigDO = channelPayOrderQueryContext.getProviderChannelConfigDO();
        String channelConfig = providerChannelConfigDO.getParamsConfig();
        // 配置转换
        EasyPayConfig easyPayConfig = JsonUtils.parseObject(channelConfig, EasyPayConfig.class);
        PayOrderDO payOrderDO = channelPayOrderQueryContext.getPayOrderDO();
        MerchantAppChannelDO merchantAppChannelDO = channelPayOrderQueryContext.getMerchantAppChannelDO();
        try {

            Map<String, Map<String, Object>> reqBody = new HashMap<>();
            Map<String, Object> reqInfo = new HashMap<>();
            reqInfo.put("mchtCode", merchantAppChannelDO.getSubMchId());
            reqBody.put("reqInfo", reqInfo);

            Map<String, Object> reqOrderInfo = new HashMap<>();
            reqOrderInfo.put("orgTrace", IdUtils.getSnowflake().nextIdStr());
            reqOrderInfo.put("oriOrgTrace", payOrderDO.getPayOrderNo());
            reqOrderInfo.put("oriTransDate", DateUtils.dateToString(payOrderDO.getCreateTime(), DatePattern.PURE_DATE_PATTERN));
            reqBody.put("reqOrderInfo", reqOrderInfo);

            Map<String, Object> payInfo = new HashMap<>();
            payInfo.put("transDate", DateUtils.dateToString(payOrderDO.getCreateTime(), DatePattern.PURE_DATE_PATTERN));
            reqBody.put("payInfo", payInfo);

            Map<String, Object> reqHeader = new HashMap<>();
            reqHeader.put("reqId", easyPayConfig.getReqId());
            reqHeader.put("transTime", DateUtils.dateToString(payOrderDO.getCreateTime(), DatePattern.PURE_DATETIME_PATTERN));
            Map<String, Object> params = new HashMap<>();
            log.info("易生订单关闭req参数:{}", JsonUtils.toJsonString(reqBody));
            params.put("reqHeader", reqHeader);
            params.put("reqBody", reqBody);
            params.put("reqSign", EasyPaySignUtil.sign(params, easyPayConfig.getRsaPrivateKey()));

            String url = domain(channelPayOrderQueryContext.isTest()) + EasyPayConstant.TRADE_CLOSE;
            String response = HttpUtils.post(url, params);
            log.info("易生订单关闭返回参数:{}", response);
            // 响应报文验签
            JSONObject res = JsonUtils.parseObj(response);
            JSONObject resHeader = res.getJSONObject("rspHeader");
            JSONObject rspBody = res.getJSONObject("rspBody");
            if ("000000".equals(resHeader.getStr("rspCode"))) {
                JSONObject respStateInfo = rspBody.getJSONObject("respStateInfo");
                if (!"000000".equals(respStateInfo.getStr("respCode"))) {
                    String respDesc = respStateInfo.getStr("respDesc");
                    channelPayOrderQueryContext.setProcessStatus(Boolean.FALSE);
                    if (StringUtils.hasText(respDesc)) {
                        channelPayOrderQueryContext.setRemark(respDesc);
                    }
                    else {
                        channelPayOrderQueryContext.setRemark("易生提交支付订单关闭返回错误信息为空,错误码为:" + respStateInfo.getStr("respCode"));
                    }
                    return;
                }
                PayOrderDO updartePayOrderDO = new PayOrderDO();
                switch (respStateInfo.getStr("transState")) {
                    case "C":
                        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.CLOSE.getCode());
                        break;
                    case "1":
                        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.PAYING.getCode());
                        break;
                    case "A":
                        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.CANCEL.getCode());
                        break;
                }

                JSONObject respOrderInfo = rspBody.getJSONObject("respOrderInfo");
                updartePayOrderDO.setInsOrderNo(respOrderInfo.getStr("outTrace"));
                updartePayOrderDO.setChannelOrderNo(respOrderInfo.getStr("pcTrace"));

                JSONObject settleRespParamInfo = rspBody.getJSONObject("settleRespParamInfo");
                if (!Objects.isNull(settleRespParamInfo)) {
                    updartePayOrderDO.setSettlementAmount(MerchantUtils.divide(new BigDecimal(settleRespParamInfo.getStr("finalAmt")), new BigDecimal(100)));
                }
                channelPayOrderQueryContext.setUpdartePayOrderDO(updartePayOrderDO);
            }
            else {
                String respDesc = resHeader.getStr("rspInfo");
                channelPayOrderQueryContext.setProcessStatus(Boolean.FALSE);
                if (StringUtils.hasText(respDesc)) {
                    channelPayOrderQueryContext.setRemark(respDesc);
                }
                else {
                    channelPayOrderQueryContext.setRemark("易生提交支付订单关闭返回错误信息为空,错误码为:" + resHeader.getStr("rspCode"));
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("易生支付订单关闭请求失败 message:{}", e.getMessage(), e);
            channelPayOrderQueryContext.setRemark("易生支付订单关闭请求失败,失败信息" + e.getMessage());
            channelPayOrderQueryContext.setProcessStatus(Boolean.FALSE);
            // channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.APPROVE_REFUSE);
        }
    }

    /**
     * 易生查询关闭订单状态
     *
     * @param channelPayOrderQueryContext
     */
    public void commonQueryChannelClosePayOrder(ChannelPayOrderQueryContext channelPayOrderQueryContext) {
        // 易生无此接口
        PayOrderDO updartePayOrderDO = new PayOrderDO();
        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.CLOSE.getCode());
        channelPayOrderQueryContext.setUpdartePayOrderDO(updartePayOrderDO);
    }

    /**
     * 易生订单退款
     *
     * @param channelRefundPayOrderContext
     */
    public void commonRefundChannelPayOrder(ChannelRefundPayOrderContext channelRefundPayOrderContext) {
        ProviderChannelConfigDO providerChannelConfigDO = channelRefundPayOrderContext.getProviderChannelConfigDO();
        String channelConfig = providerChannelConfigDO.getParamsConfig();
        // 配置转换
        EasyPayConfig easyPayConfig = JsonUtils.parseObject(channelConfig, EasyPayConfig.class);

        PayOrderDO payOrderDO = channelRefundPayOrderContext.getPayOrderDO();
        RefundOrderDO refundOrderDO = channelRefundPayOrderContext.getRefundOrderDO();
        MerchantAppChannelDO merchantAppChannelDO = channelRefundPayOrderContext.getMerchantAppChannelDO();
        try {
            Map<String, Map<String, Object>> reqBody = new HashMap<>();
            Map<String, Object> reqInfo = new HashMap<>();
            reqInfo.put("mchtCode", merchantAppChannelDO.getSubMchId());
            reqBody.put("reqInfo", reqInfo);

            Map<String, Object> reqOrderInfo = new HashMap<>();
            reqOrderInfo.put("orgTrace", refundOrderDO.getRefundOrderNo());
            reqOrderInfo.put("oriOrgTrace", payOrderDO.getPayOrderNo());
            reqOrderInfo.put("oriTransDate", DateUtils.dateToString(payOrderDO.getCreateTime(), DatePattern.PURE_DATE_PATTERN));
            reqOrderInfo.put("refundAmount", MerchantUtils.YuanToFen(refundOrderDO.getRefundAmount()).toString());
            reqBody.put("reqOrderInfo", reqOrderInfo);

            Map<String, Object> payInfo = new HashMap<>();
            payInfo.put("transDate", DateUtils.getDateString(DatePattern.PURE_DATE_PATTERN));
            reqBody.put("payInfo", payInfo);

            Map<String, Object> reqHeader = new HashMap<>();
            reqHeader.put("reqId", easyPayConfig.getReqId());
            reqHeader.put("transTime", DateUtils.getDateString(DatePattern.PURE_DATETIME_PATTERN));
            Map<String, Object> params = new HashMap<>();
            params.put("reqHeader", reqHeader);
            params.put("reqBody", reqBody);
            params.put("reqSign", EasyPaySignUtil.sign(params, easyPayConfig.getRsaPrivateKey()));

            log.info("易生订单退款req参数:{}", JsonUtils.toJsonString(params));
            String url = domain(channelRefundPayOrderContext.isTest()) + EasyPayConstant.TRADE_REFUND_APPLY;
            String response = HttpUtils.post(url, params);
            log.info("易生订单退款返回参数:{}", response);
            // 响应报文验签
            JSONObject res = JsonUtils.parseObj(response);
            JSONObject resHeader = res.getJSONObject("rspHeader");
            JSONObject rspBody = res.getJSONObject("rspBody");
            if ("000000".equals(resHeader.getStr("rspCode"))) {
                JSONObject respStateInfo = rspBody.getJSONObject("respStateInfo");
                if (!"000000".equals(respStateInfo.getStr("respCode"))) {
                    String respDesc = respStateInfo.getStr("respDesc");
                    channelRefundPayOrderContext.setProcessStatus(Boolean.FALSE);
                    if (StringUtils.hasText(respDesc)) {
                        channelRefundPayOrderContext.setRemark(respDesc);
                    }
                    else {
                        channelRefundPayOrderContext.setRemark("易生提交退款订单查询返回错误信息为空,错误码为:" + respStateInfo.getStr("respCode"));
                    }
                    return;
                }
                RefundOrderDO updateRefundOrderDO = new RefundOrderDO();
                updateRefundOrderDO.setBankCode(respStateInfo.getStr("appendRetCode"));
                updateRefundOrderDO.setBankMsg(respStateInfo.getStr("appendRetMsg"));
//                updateRefundOrderDO.set
                JSONObject settleRespParamInfo = rspBody.getJSONObject("settleRespParamInfo");
                switch (respStateInfo.getStr("transState")) {
                    case "A":
                    case "9":
                    case "E":
                    case "C":
                    case "X":
                        updateRefundOrderDO.setRefundStatus(PayOrderEnums.REFUND_STATUS.FAIL.getCode());
                        break;
                    case "0":
                        updateRefundOrderDO.setRefundStatus(PayOrderEnums.REFUND_STATUS.REFUND.getCode());
                        updateRefundOrderDO.setSuccessTime(DateUtils.shanghaiDate(settleRespParamInfo.getStr("settleTime")));
                        break;
                    default:
                        updateRefundOrderDO.setRefundStatus(PayOrderEnums.REFUND_STATUS.REFUNDING.getCode());
                        break;
                }

                channelRefundPayOrderContext.setUpdateRefundOrderDO(updateRefundOrderDO);
            }
            else {
                String respDesc = resHeader.getStr("rspInfo");
                channelRefundPayOrderContext.setProcessStatus(Boolean.FALSE);
                if (StringUtils.hasText(respDesc)) {
                    channelRefundPayOrderContext.setRemark(respDesc);
                }
                else {
                    channelRefundPayOrderContext.setRemark("易生提交退款订单返回错误信息为空,错误码为:" + resHeader.getStr("rspCode"));
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("易生提交退款订单请求失败 message:{}", e.getMessage(), e);
            channelRefundPayOrderContext.setRemark("易生提交退款订单请求失败,失败信息" + e.getMessage());
            channelRefundPayOrderContext.setProcessStatus(Boolean.FALSE);
        }
    }

    /**
     * 易生订单退款状态查询
     *
     * @param channelRefundPayOrderContext
     */
    public void commonQueryRefundChannelPayOrder(ChannelRefundPayOrderContext channelRefundPayOrderContext) {
        ProviderChannelConfigDO providerChannelConfigDO = channelRefundPayOrderContext.getProviderChannelConfigDO();
        String channelConfig = providerChannelConfigDO.getParamsConfig();
        // 配置转换
        EasyPayConfig easyPayConfig = JsonUtils.parseObject(channelConfig, EasyPayConfig.class);

        RefundOrderDO refundOrderDO = channelRefundPayOrderContext.getRefundOrderDO();
        MerchantAppChannelDO merchantAppChannelDO = channelRefundPayOrderContext.getMerchantAppChannelDO();
        try {

            Map<String, Map<String, Object>> reqBody = new HashMap<>();
            Map<String, Object> reqInfo = new HashMap<>();
            reqInfo.put("mchtCode", merchantAppChannelDO.getSubMchId());
            reqBody.put("reqInfo", reqInfo);

            Map<String, Object> reqOrderInfo = new HashMap<>();
            reqOrderInfo.put("orgTrace", IdUtils.getSnowflake().nextIdStr());
            reqOrderInfo.put("oriOrgTrace", refundOrderDO.getRefundOrderNo());
            reqOrderInfo.put("oriTransDate", DateUtils.dateToString(refundOrderDO.getCreateTime(), DatePattern.PURE_DATE_PATTERN));
            reqBody.put("reqOrderInfo", reqOrderInfo);

            Map<String, Object> payInfo = new HashMap<>();
            payInfo.put("transDate", DateUtils.getDateString(DatePattern.PURE_DATE_PATTERN));
            reqBody.put("payInfo", payInfo);

            Map<String, Object> reqHeader = new HashMap<>();
            reqHeader.put("reqId", easyPayConfig.getReqId());
            reqHeader.put("transTime", DateUtils.getDateString(DatePattern.PURE_DATETIME_PATTERN));
            Map<String, Object> params = new HashMap<>();
            params.put("reqHeader", reqHeader);
            params.put("reqBody", reqBody);
            params.put("reqSign", EasyPaySignUtil.sign(params, easyPayConfig.getRsaPrivateKey()));

            log.info("易生订单退款查询req参数:{}", JsonUtils.toJsonString(params));
            String url = domain(channelRefundPayOrderContext.isTest()) + EasyPayConstant.TRADE_REFUND_QUERY;
            String response = HttpUtils.post(url, params);
            log.info("易生订单退款查询返回参数:{}", response);

            JSONObject res = JsonUtils.parseObj(response);
            JSONObject resHeader = res.getJSONObject("rspHeader");
            JSONObject rspBody = res.getJSONObject("rspBody");
            if ("000000".equals(resHeader.getStr("rspCode"))) {
                JSONObject respStateInfo = rspBody.getJSONObject("respStateInfo");
                if (!"000000".equals(respStateInfo.getStr("respCode"))) {
                    String respDesc = respStateInfo.getStr("respDesc");
                    channelRefundPayOrderContext.setProcessStatus(Boolean.FALSE);
                    if (StringUtils.hasText(respDesc)) {
                        channelRefundPayOrderContext.setRemark(respDesc);
                    }
                    else {
                        channelRefundPayOrderContext.setRemark("易生提交退款订单查询返回错误信息为空,错误码为:" + respStateInfo.getStr("respCode"));
                    }
                    return;
                }
                RefundOrderDO updateRefundOrderDO = new RefundOrderDO();
                updateRefundOrderDO.setBankCode(respStateInfo.getStr("appendRetCode"));
                updateRefundOrderDO.setBankMsg(respStateInfo.getStr("appendRetMsg"));
                switch (respStateInfo.getStr("transState")) {
                    case "0":
                    case "R":
                        updateRefundOrderDO.setRefundStatus(PayOrderEnums.REFUND_STATUS.REFUND.getCode());
                        break;
                    case "A":
                    case "9":
                    case "E":
                    case "C":
                        updateRefundOrderDO.setRefundStatus(PayOrderEnums.REFUND_STATUS.FAIL.getCode());
                        break;
                }
                channelRefundPayOrderContext.setUpdateRefundOrderDO(updateRefundOrderDO);
            }
            else {
                String respDesc = resHeader.getStr("rspInfo");
                channelRefundPayOrderContext.setProcessStatus(Boolean.FALSE);
                if (StringUtils.hasText(respDesc)) {
                    channelRefundPayOrderContext.setRemark(respDesc);
                }
                else {
                    channelRefundPayOrderContext.setRemark("易生提交退款订单返回错误信息为空,错误码为:" + resHeader.getStr("rspCode"));
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("易生退款订单查询请求失败 message:{}", e.getMessage(), e);
            channelRefundPayOrderContext.setRemark("易生退款订单查询请求失败,失败信息" + e.getMessage());
            channelRefundPayOrderContext.setProcessStatus(Boolean.FALSE);
        }
    }

    public EasypayAppChannelParams easyPayAppChannelParams(MerchantAppChannelDO merchantAppChannelDO) {
        return JsonUtils.parseObject(merchantAppChannelDO.getAppConfigJson(), EasypayAppChannelParams.class);
    }

    public String domain(boolean test) {
        return test ? EasyPayConstant.PAY_ORDER_DOMAIN_TEST : EasyPayConstant.PAY_ORDER_DOMAIN_PROD;
    }

    void processFund(Map<String, Object> settleParamInfo, Map<String,Object> reqBody, PayOrderDO payOrderDO, List<PayOrderFundDto> accounts,
            EasypayAppChannelParams easypayAppChannelParams) {
        // 0：非分账交易
        // 1：交易后分账
        // 2：交易中分账

        // 分账类型 ，0或空=无分账，1=实时分账，2=延时分账，3=商户 预设默认分账
        if (payOrderDO.getFundProcessType() == null || payOrderDO.getFundProcessType() == 0) {
            settleParamInfo.put("splitSettleFlag", "0");
            settleParamInfo.put("patnerSettleFlag", "1");
            return;
        }
        Integer amount = MerchantUtils.YuanToFen(payOrderDO.getAmount());
        switch (payOrderDO.getFundProcessType()) {
            case 1:
                SeparateInfo separateInfo = new SeparateInfo();
                separateInfo.setOriSeparateMchtCode(easypayAppChannelParams.getCustomerNo());
                separateInfo.setSeparaBatchTrace(accounts.get(0).getBatchNo());
                List<SeparateOrderDetailList> separateOrderDetails = new ArrayList<>();
                accounts.stream().forEach(account -> {
                    SeparateOrderDetailList separateOrderDetailList = new SeparateOrderDetailList();
                    separateOrderDetailList.setIsD0("1");
                    separateOrderDetailList.setReceiveMchtCode(account.getAccountNo());
                    separateOrderDetailList.setSeparateTrade(account.getBatchNoDetail());
                    separateOrderDetailList.setSepaTransAmount(MerchantUtils.YuanToFen(new BigDecimal(account.getAmount())));
                    separateOrderDetailList.setSepaFeeAmount(new BigDecimal(account.getSepaFeeRatio()).divide(new BigDecimal(100)).multiply(new BigDecimal(amount)).setScale(2).intValue());
                    separateOrderDetailList.setSubject(account.getDescription());
                    separateOrderDetails.add(separateOrderDetailList);
                });
                separateInfo.setSeparateOrderDetailList(separateOrderDetails);
                int sum = separateOrderDetails.stream().mapToInt(separateOrderDetailList -> separateOrderDetailList.getSepaTransAmount()).sum();
                int sepaFeeAmount = separateOrderDetails.stream().mapToInt(separateOrderDetailList -> separateOrderDetailList.getSepaFeeAmount()).sum();
                if (amount > sum) {
                    SeparateOrderDetailList separateOrderDetailList = new SeparateOrderDetailList();
                    separateOrderDetailList.setIsD0(accounts.get(0).getPeriodType().toString());
                    separateOrderDetailList.setReceiveMchtCode(easypayAppChannelParams.getCustomerNo());
                    separateOrderDetailList.setSeparateTrade(payOrderDO.getPayOrderNo()+"_1");
                    separateOrderDetailList.setSepaTransAmount(amount - sum);
                    separateOrderDetailList.setSepaFeeAmount(amount-sepaFeeAmount);
                    separateOrderDetailList.setSubject("多余部分分给自己");
                    separateOrderDetails.add(separateOrderDetailList);
                }
                separateInfo.setTransSumAmt(amount);
                separateInfo.setTransSumCount(separateOrderDetails.size());
                settleParamInfo.put("splitSettleFlag", "2");
                settleParamInfo.put("patnerSettleFlag", "0");
                reqBody.put("separateInfo", BeanUtil.beanToMap(separateInfo));
                return;
            case 2:
            case 3:
                settleParamInfo.put("splitSettleFlag", "1");
                settleParamInfo.put("patnerSettleFlag", "0");
                return;
            default:
                settleParamInfo.put("splitSettleFlag", "0");
                settleParamInfo.put("patnerSettleFlag", "1");
        }
    }

    public Integer expireMinute(Long time) {
        if (time == null) {
            return 180;
        }
        return (int) (time - System.currentTimeMillis()) / 1000;
    }
}
